package problems.daily;

import java.util.HashSet;
import java.util.Set;

/**
 * 1032. 字符流
 * <p>https://leetcode.cn/problems/stream-of-characters/</p>
 *
 * @author habitplus
 * @since 2023/3/24 10:34
 */
public class DT1032 {

    /**
     * Your StreamChecker object will be instantiated and called as such:
     * StreamChecker obj = new StreamChecker(words);
     * boolean param_1 = obj.query(letter);
     */
    class StreamChecker {
        private final Set<String> set;
        private final int min;
        // private final int max;
        private char[] data;

        private int size;

        public StreamChecker(String[] words) {
            int mint = 201;
            int maxt = 0;
            set = new HashSet<>();
            for (String w : words) {
                set.add(w);
                mint = Math.min(mint, w.length());
                maxt = Math.max(maxt, w.length());
            }
            min = mint;
            data = new char[maxt];
            size = 0;
        }

        public boolean query(char letter) {
            put(letter);
            if (size < min) return false;
//            StringBuilder sb = new StringBuilder(new String(data, size + 1 - min, min));
            StringBuilder sb = new StringBuilder(new String(data, size + 1 - min, min - 1));

            for (int i = min; i <= size; ++i) {
                sb.insert(0, data[size - i]);
                if (set.contains(sb.toString())) {
                    return true;
                }
            }

            return false;
        }

        private void put(char c) {
            int cnt = data.length;
            if (size >= cnt) {
                // 已存满
                // System.arraycopy(data, 1, data, 0, cnt - 1);
                for (int i = 0; i < cnt - 1; ++i) {
                    data[i] = data[i + 1];
                }
                data[cnt - 1] = c;
                return;
            }
            data[size++] = c;
        }

    }

}
